package com.jjc.MyWebApp.Routes.MainController;

import com.jfinal.aop.Before;
import com.jfinal.i18n.Res;
import com.jfinal.log.Log;
import com.jjc.MyWebApp.Annotation.Controller;
import com.jjc.MyWebApp.Constant.ConfigConstant;
import com.jjc.MyWebApp.Constant.UserConstant;
import com.jjc.MyWebApp.Constant.WebContextConstant;
import com.jjc.MyWebApp.Interceptor.AuthInterceptor;
import com.jjc.MyWebApp.Model.AjaxModel.JsonModel;
import com.jjc.MyWebApp.Model.User;
import com.jjc.MyWebApp.Plugin.ServicePlugin;
import com.jjc.MyWebApp.Routes.BaseController;
import com.jjc.MyWebApp.Service.UserService;
import com.jjc.MyWebApp.Validator.LoginValidator;
import com.jjc.MyWebApp.kit.UUIDKit;

/**
 * Created by jiajianchang on 2017/4/29.
 */
@Controller(value = {"/userlogin"}, viewPath = "/main")
public class loginController extends BaseController {

    private static final Log log = Log.getLog(loginController.class);

    private UserService userService = (UserService) ServicePlugin.getService("userService");

    public void login() {
        User user = getCurrentUser();
        if (user != null)
            redirect("/");
        else
            render("login.html");
    }

    public void register() {
        render("register.html");
    }

    @Before(LoginValidator.class)
    public void loginSubmit() {
        Res res = getAttr("_res");
        String Email = getPara("user.user_email");
        String password = getPara("passWord");
        int lock = userService.login(this, Email, password, false);
        switch (lock) {
            case UserConstant.User_Login_info_0:
                renderError(getI18nVal("MyWebApp.Login.signIn.Error_0"));
                break;
            case UserConstant.User_Login_info_1:
                renderError(getI18nVal("MyWebApp.Login.signIn.Error_1"));
                break;
            case UserConstant.User_Login_info_2:
                renderError(getI18nVal("MyWebApp.Login.signIn.Error_2"));
                break;
            case UserConstant.User_Login_info_3:
                renderError(getI18nVal("MyWebApp.Login.signIn.Error_3"));
                break;
            case UserConstant.User_Login_info_4:
                renderSuccess(getI18nVal("MyWebApp.Login.signIn.Success"), "/");
                break;
        }
    }

    @Before(LoginValidator.class)
    public void registerSubmit() {
        String password = getPara("passWord");
        User user = getModel(User.class, "user");
        if (userService.insert(UUIDKit.getUUID(), password, user)) {
            renderJson(JsonModel.successMsg(getI18nVal("MyWebApp.Login.signUp.Success"), "/userlogin/login"));
        } else {
            renderJson(JsonModel.errorMsg(getI18nVal("MyWebApp.Login.signUp.Error")));
        }
    }

    /**
     * 注销
     */
    public void logout() {
        removeCookie(WebContextConstant.cookie_authmark);
        redirect("/");
    }

}
